const Koa = require('koa')
const Router = require('koa-router')
const jwt = require('jsonwebtoken')

const app = new Koa()
const router = new Router()

async function time (ctx, next, app) {
  const start = Date.now()
  await next()
  const ms = Date.now() - start
  var info = `${ctx.method} ${ctx.status} ${ctx.url} - ${ms} ms`
  // ctx.bug.log(ctx.request.headers)
  if (ctx.status > 400 && ctx.status < 500) {
    console.warn(info)
  } else if (ctx.status < 400) {
    console.log(info)
  } else {
    console.error(info)
  }
}

// 加密密码
const secretKey = '123456'
// 过期时间
const expiresIn = '2h'

async function authenticate (ctx, next) {
  var token = ctx.headers['authorization']
  if (!token) {
    ctx.status = 401
    return ctx.body = {
      msg: '你无权访问',
      code: 401
    }
  }
  ctx.user = jwt.verify(token, secretKey)
  return next()
}

app.use(time)

router.get('/', ctx => {
  ctx.body = 'wellcome !'
})

router.get('/token', async ctx => {
  
  var user = {id: 1, name: '张三'}

  ctx.body = jwt.sign(user, secretKey, {expiresIn})
})


router.get('/user', authenticate, async ctx => {
  ctx.body = {
    msg: '这里信息登录才能看',
    user: ctx.user
  }
})



app.use(router.routes())
app.use(router.allowedMethods())

app.listen(3000)
